package org.jeecg.modules.demo.dz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.dz.entity.*;
import org.jeecg.modules.demo.dz.service.*;
import org.jeecg.modules.demo.dz.vo.DzMaterialSkuDetailVO;
import org.jeecg.modules.demo.dz.vo.DzMaterialSkuPage;
import org.jeecg.modules.demo.dz.vo.DzMaterialSpuDetailVO;
import org.jeecg.modules.demo.manage.entity.DzMaterialSku;
import org.jeecg.modules.demo.manage.entity.DzMaterialSkuSpec;
import org.jeecg.modules.demo.manage.entity.DzMaterialSpu;
import org.jeecg.modules.demo.manage.service.IDzMaterialSkuService;
import org.jeecg.modules.demo.manage.service.IDzMaterialSkuSpecService;
import org.jeecg.modules.demo.manage.service.IDzMaterialSpuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @Description: 物料sku
* @Author: jack
* @Date:   2024-11-12
* @Version: V1.0
*/
@Api(tags="物料sku")
@RestController
@RequestMapping("/dz/dzMaterialSku")
@Slf4j
public class MiniAppSkuController {
   @Autowired
   private IDzMaterialSkuService dzMaterialSkuService;
   @Autowired
   private IDzMaterialSkuSpecService dzMaterialSkuSpecService;
   /*@Autowired
   private IDzMaterialSkuImageService dzMaterialSkuImageService;*/
   @Autowired
   private IDzMaterialSpuService dzMaterialSpuService;
   @Autowired
   private IDzChooseItemService dzChooseItemService;
   @Autowired
   private IDzCategoryService dzCategoryService;
   @Autowired
   private IDzBrandService dzBrandService;
   @Autowired
   private IDzSupplierService dzSupplierService;
   @Autowired
   IDzFavoriteService dzFavoriteService;
   @Autowired
   IDzSupplierPhoneService dzSupplierPhoneService;

   /**
    * 分页列表查询
    *
    * @param dzMaterialSku
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "物料sku-分页列表查询")
   @ApiOperation(value="物料sku-分页列表查询", notes="物料sku-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<DzMaterialSku>> queryPageList(DzMaterialSku dzMaterialSku,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     HttpServletRequest req) {
       QueryWrapper<DzMaterialSku> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialSku, req.getParameterMap());
       Page<DzMaterialSku> page = new Page<DzMaterialSku>(pageNo, pageSize);
       IPage<DzMaterialSku> pageList = dzMaterialSkuService.page(page, queryWrapper);
       return Result.OK(pageList);
   }




   @ApiOperation(value="物料主表-小程序查询物料列表", notes="物料主表-小程序查询物料列表")
   @GetMapping(value = "/pageMiniSkuList")
   public Result<IPage<DzMaterialSkuPage>> pageMiniSkuList(DzMaterialSku dzMaterialSku,
                                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                           @RequestParam(name="keyWord",required = false) String keyWord,
                                                           @RequestParam(name="type",required = false) String type,
                                                           @RequestParam(name="categoryId",required = false) String categoryId,
                                                           @RequestParam(name="chooseItemId",required = false) String chooseItemId,
                                                           HttpServletRequest req) {
       QueryWrapper<DzMaterialSku> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialSku, req.getParameterMap());
       queryWrapper.eq("state",1);
       if("xuancai".equals(type)){
           queryWrapper.isNotNull("choose_item_id");
       }
       if(StringUtils.isNotEmpty(categoryId)){
           //DzCategory dzCategory = dzCategoryService.getById(categoryId);
           queryWrapper.eq("category_id",categoryId);
       }
       if(StringUtils.isNotEmpty(chooseItemId)){
           queryWrapper.likeRight("choose_item_id",chooseItemId);
       }
       if(StringUtils.isNotEmpty(keyWord)){
           queryWrapper.and(wrapper -> wrapper.like("brand_name",keyWord)
                   .or().like("spu_name",keyWord).or().like("category_full_path",keyWord));
       }
       Page<DzMaterialSku> page = new Page<DzMaterialSku>(pageNo, pageSize);
       IPage<DzMaterialSku> pageList = dzMaterialSkuService.page(page, queryWrapper);

       Page<DzMaterialSkuPage> pageRes = new Page<DzMaterialSkuPage>(pageNo, pageSize);

       List<DzMaterialSku> records = pageList.getRecords();

       if(CollectionUtil.isNotEmpty(records)){
           List<DzMaterialSkuPage> resultList = new ArrayList<>();
           records.stream().forEach(r->{
               DzMaterialSkuPage dzMaterialSkuPage = BeanUtil.copyProperties(r, DzMaterialSkuPage.class);
               resultList.add(dzMaterialSkuPage);
           });

           pageRes.setRecords(resultList);
           List<String> spuIds = resultList.stream().map(r -> r.getSpuId()).collect(Collectors.toList());
           List<DzMaterialSpu> dzMaterialSpus = dzMaterialSpuService.listByIds(spuIds);
           Map<String, DzMaterialSpu> spuMap = dzMaterialSpus.stream().collect(Collectors.toMap(DzMaterialSpu::getId, spu -> spu));
           resultList.stream().forEach(sku -> {
               DzMaterialSpu dzMaterialSpu = spuMap.get(sku.getSpuId());
               if(dzMaterialSpu != null){
                   sku.setName(dzMaterialSpu.getName());
               }
           });
       }

       return Result.OK(pageRes);
   }

   @ApiOperation(value="物料主表-小程序查询物料列表", notes="物料主表-小程序查询物料列表")
   @GetMapping(value = "/getDetailById")
   public Result<DzMaterialSpuDetailVO> getDetailById(@RequestParam(name = "id") String id){

       DzMaterialSku dzMaterialSku = dzMaterialSkuService.getById(id);
       if(dzMaterialSku==null) {
           return Result.error("未找到对应数据");
       }

       LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

       DzMaterialSpuDetailVO spuDetailVO = new DzMaterialSpuDetailVO();

       List<DzMaterialSkuDetailVO> skuDetailList = new ArrayList<>();

       String spuId = dzMaterialSku.getSpuId();
       List<DzMaterialSku> skuList = dzMaterialSkuService
               .lambdaQuery().eq(DzMaterialSku::getSpuId,spuId).eq(DzMaterialSku::getState,1).list();

       Map<String, DzFavorite> favoriteMap = new HashMap<>();
       if(CollectionUtil.isNotEmpty(skuList)){
           List<String> skuIds = skuList.stream().map(sku -> sku.getId()).collect(Collectors.toList());
           if(loginUser != null){
               List<DzFavorite> favorites = dzFavoriteService.lambdaQuery().eq(DzFavorite::getType, "sku").in(DzFavorite::getBusinessId, skuIds).list();
               /*favoriteMap.putAll(favorites.stream().collect(Collectors.toMap(DzFavorite::getBusinessId,favorite -> favorite)));*/
               for (int i = 0; i < favorites.size(); i++) {
                   DzFavorite dzFavorite = favorites.get(i);
                   favoriteMap.put(dzFavorite.getBusinessId(),dzFavorite);
               }
           }
       }


       DzMaterialSpu spu = dzMaterialSpuService.getById(spuId);
       DzBrand dzBrand = dzBrandService.getById(spu.getBrandId());
       DzSupplier dzSupplier = dzSupplierService.getById(spu.getSupplierId());
       List<DzSupplierPhone> phoneList = dzSupplierPhoneService.lambdaQuery().eq(DzSupplierPhone::getSupplierId, spu.getSupplierId()).list();

       List<DzMaterialSkuSpec> spuSpecList = dzMaterialSkuSpecService.lambdaQuery()
                       .eq(DzMaterialSkuSpec::getSpuId, spuId)
                       .eq(DzMaterialSkuSpec::getSpecType, "spu")
                       .orderByAsc(DzMaterialSkuSpec::getOrderNo)
                       .list();
       spuDetailVO.setUnitName("个");
       spuDetailVO.setSpuName(spu.getName());
       spuDetailVO.setBrandName(dzBrand != null ? dzBrand.getName() : "");
       spuDetailVO.setBrandKind(dzBrand != null ? dzBrand.getBrandKind() : "");
       spuDetailVO.setSupplierId(spu.getSupplierId());
       spuDetailVO.setSupplierName(dzSupplier != null ? dzSupplier.getName() : "");
       spuDetailVO.setDetailHtml(spu.getDetailHtml());
       spuDetailVO.setSpuId(spuId);
       spuDetailVO.setPhoneList(phoneList);
       if(CollectionUtil.isNotEmpty(skuList)){
           for (int i = 0; i < skuList.size(); i++) {
               dzMaterialSku = skuList.get(i);
               DzMaterialSkuDetailVO detailVO = new DzMaterialSkuDetailVO();
               detailVO.setCollectFlag(favoriteMap.containsKey(dzMaterialSku.getId()));
               detailVO.setId(dzMaterialSku.getId());
               detailVO.setOriginPrice(dzMaterialSku.getOriginPrice());
               detailVO.setNowPrice(dzMaterialSku.getNowPrice());

               List<DzMaterialSkuSpec> skuSpecList = dzMaterialSkuSpecService.lambdaQuery()
                       .eq(DzMaterialSkuSpec::getSkuId, dzMaterialSku.getId())
                       .eq(DzMaterialSkuSpec::getSpecType, "sku")
                       .orderByAsc(DzMaterialSkuSpec::getOrderNo)
                       .list();
               List allSpecList = new ArrayList();
               allSpecList.addAll(spuSpecList);
               allSpecList.addAll(skuSpecList);
               detailVO.setSpecList(allSpecList);

               /*List<DzMaterialSkuImage> imageList = dzMaterialSkuImageService.lambdaQuery()
                       .eq(DzMaterialSkuImage::getSkuId, dzMaterialSku.getId())
                       .eq(DzMaterialSkuImage::getIsDeleted, 0)
                       .orderByAsc(DzMaterialSkuImage::getId)
                       .list();*/
               detailVO.setImageUrl(dzMaterialSku.getImage());
               //detailVO.setImageList(imageList);
               skuDetailList.add(detailVO);
           }
       }

       spuDetailVO.setSkuList(skuDetailList);

       return Result.ok(spuDetailVO);
   }

   /**
    *   添加
    *
    * @param dzMaterialSkuPage
    * @return
    */
   @AutoLog(value = "物料sku-添加")
   @ApiOperation(value="物料sku-添加", notes="物料sku-添加")
   //@RequiresPermissions("org.jeecg.modules.demo:dz_material_sku:add")
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody DzMaterialSkuPage dzMaterialSkuPage) {
       DzMaterialSku dzMaterialSku = new DzMaterialSku();
       BeanUtils.copyProperties(dzMaterialSkuPage, dzMaterialSku);
       //dzMaterialSkuService.saveMain(dzMaterialSku, dzMaterialSkuPage.getDzMaterialSkuSpecList(),dzMaterialSkuPage.getDzMaterialSkuImageList());
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param dzMaterialSkuPage
    * @return
    */
   @AutoLog(value = "物料sku-编辑")
   @ApiOperation(value="物料sku-编辑", notes="物料sku-编辑")
   //@RequiresPermissions("org.jeecg.modules.demo:dz_material_sku:edit")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
   public Result<String> edit(@RequestBody DzMaterialSkuPage dzMaterialSkuPage) {
       DzMaterialSku dzMaterialSku = new DzMaterialSku();
       BeanUtils.copyProperties(dzMaterialSkuPage, dzMaterialSku);
       DzMaterialSku dzMaterialSkuEntity = dzMaterialSkuService.getById(dzMaterialSku.getId());
       if(dzMaterialSkuEntity==null) {
           return Result.error("未找到对应数据");
       }
       //dzMaterialSkuService.updateMain(dzMaterialSku, dzMaterialSkuPage.getDzMaterialSkuSpecList(),dzMaterialSkuPage.getDzMaterialSkuImageList());
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "物料sku-通过id删除")
   @ApiOperation(value="物料sku-通过id删除", notes="物料sku-通过id删除")
   //@RequiresPermissions("org.jeecg.modules.demo:dz_material_sku:delete")
   @DeleteMapping(value = "/delete")
   public Result<String> delete(@RequestParam(name="id",required=true) String id) {
       //dzMaterialSkuService.delMain(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "物料sku-批量删除")
   @ApiOperation(value="物料sku-批量删除", notes="物料sku-批量删除")
   //@RequiresPermissions("org.jeecg.modules.demo:dz_material_sku:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       //this.dzMaterialSkuService.delBatchMain(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功！");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "物料sku-通过id查询")
   @ApiOperation(value="物料sku-通过id查询", notes="物料sku-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<DzMaterialSku> queryById(@RequestParam(name="id",required=true) String id) {
       DzMaterialSku dzMaterialSku = dzMaterialSkuService.getById(id);
       if(dzMaterialSku==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(dzMaterialSku);

   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "sku属性通过主表ID查询")
   @ApiOperation(value="sku属性主表ID查询", notes="sku属性-通主表ID查询")
   @GetMapping(value = "/queryDzMaterialSkuSpecByMainId")
   public Result<List<DzMaterialSkuSpec>> queryDzMaterialSkuSpecListByMainId(@RequestParam(name="id",required=true) String id) {
       List<DzMaterialSkuSpec> dzMaterialSkuSpecList = dzMaterialSkuSpecService.selectByMainId(id);
       return Result.OK(dzMaterialSkuSpecList);
   }

}
